package swing.chapter03;

import swing.util.SwingConsle;

import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 *  （非下拉）列表框
 */
public class List extends JFrame {
    private String [] language = {"Java", "C++", "Python", "R", "Go", "Javascript", "Html", "Jsp", "PHP"};

    private DefaultListModel<String> litems = new DefaultListModel();
    private JList<DefaultButtonModel> lst = new JList(litems);
    private JTextArea t = new JTextArea(language.length, 20);
    private JButton b = new JButton("Add Item");
    private int count = 0;

    private ActionListener bl = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if(count < language.length){
                litems.add(0, language[count++]);
            }else{
                b.setEnabled(false);
            }
        }
    };

    private ListSelectionListener lsl = new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            if(e.getValueIsAdjusting()) return ;
            t.setText("");

            for(Object item : lst.getSelectedValues()){
                t.append(item + "\n");
            }
        }
    };

    public List(){
        t.setEditable(false);
        setLayout(new FlowLayout());
        Border brd = BorderFactory.createMatteBorder(1,1,2,2,Color.black);
        lst.setBorder(brd);
        t.setBorder(brd);

        for(int i=0;i<4;i++){
            litems.addElement(language[count++]);
        }
        add(t);
        add(lst);
        add(b);
        lst.addListSelectionListener(lsl);
        b.addActionListener(bl);
    }

    public static void main(String[] args) {
        SwingConsle.run(new List(), 250, 375);
    }

}
